﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;

using Common;
using AuthServer.JwtService;
using SqlSugar;
using Models.Entity;
using AutoMapper;
using BusinessInterface;
using DTOModels.User;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;

namespace AuthServer
{
    /// <summary>
    /// 专属用于登录的，颁发Token
    /// </summary>
    public static class AccountApiExt
    {
        /// <summary>
        /// 登录账号:JHY-admin /richard   123456
        /// </summary>
        /// <param name="app"></param>
        public static void LoginApi(this WebApplication app)
        {
            //JWT： 对称加密解密的 token  非对称的加解密token
            //登录，颁发Token
            app.MapPost("auth/Account", ([FromServices] CustomJWTService _iJWTService, [FromServices] IUserManagerService _IUserManagerService, User u) =>
            {
                //SqlSugar的框架
                #region 根据用户的名称& 密码查询到的用户的信息和各种权限
                SysUserInfo? userinfo = _IUserManagerService.Login(u.Name!, u.Password!);

                if (userinfo == null)
                {
                    return new ApiResultData<object>()
                    {
                        Success = false,
                        Message = "用户名或者密码错误"
                    };
                }
                #endregion
                //如果要颁发Token，必须验证用户名 & 密码，链接数据库
                string accessToken = _iJWTService.CreateToken(userinfo, out string refreshtoken);
                return new ApiResultData<object>()
                {
                    Success = true,
                    Message = "登录成功",
                    Data = new
                    {
                        UserName = userinfo.Name,
                        userinfo.Imageurl
                    },
                    OValue = new
                    {
                        RefreshToken = refreshtoken,
                        Accesstoken = accessToken
                    }
                };
            });


            //原token过期后，前端检测到token 会发出刷新Token的请求，服务端返回新的Token
            app.MapGet("auth/Account",
             [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
            ([FromServices] CustomJWTService _iJWTService, [FromServices] IMemoryCache _IMemoryCache, HttpContext context) =>
             {
                 string refreshtokenGuid = context?.User?.FindFirst("refreshtokenGuid")?.Value;
                 if (string.IsNullOrWhiteSpace(refreshtokenGuid))
                 {
                     return new ApiResult()
                     {
                         Success = false,
                         Message = "已过期需要重新登录",
                     };
                 }
                 SysUserInfo? userInfo = _IMemoryCache.Get<SysUserInfo>(refreshtokenGuid);
                 if (userInfo == null)
                 {
                     return new ApiResult()
                     {
                         Success = false,
                         Message = "已过期需要重新登录",
                     };
                 }
                 string token = _iJWTService.CreateToken(userInfo, out string refreshToken);
                 _IMemoryCache.Remove(refreshtokenGuid);
                 return new ApiResultData<string>()
                 {
                     Success = true,
                     Message = "Token刷新成功",
                     Data = token,
                     OValue = refreshToken
                 };
             }).WithGroupName("v1").WithDescription("刷新Token,使用RreshToken换新Token");


            //注销登录
            app.MapPost("auth/Logout", ([FromServices] CustomJWTService _iJWTService, [FromServices] IMemoryCache _IMemoryCache, HttpContext context) =>
            {
                string refreshtokenGuid = context?.User?.FindFirst("refreshtokenGuid")?.Value;
                if (string.IsNullOrWhiteSpace(refreshtokenGuid))
                {
                    return new ApiResult()
                    {
                        Success = true,
                        Message = "已登出",
                    };
                }
                SysUserInfo? userInfo = _IMemoryCache.Get<SysUserInfo>(refreshtokenGuid);
                if (userInfo != null)
                {
                    _IMemoryCache.Remove(refreshtokenGuid);
                   
                }


                return new ApiResult()
                {
                    Success = true,
                    Message = "已登出",
                };
            });
        
        
        }
    }
}
